<?php

require_once 'AppConfig.php';

class DbHelper {

    private $PDO;
    private $_config;
    private $isConnected = false;

    public function __construct() {
        // load from the default Setting
        $this->_config = AppConfig::getDbConfigure();
        // Create the connection
        try {
            $this->PDO = new PDO($this->_config["DB_DSN"], $this->_config["DB_USER"], $this->_config["DB_PWD"]);
            $this->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->isConnected = true;
        } catch (PDOException $ex) {
            print_r($ex->getMessage());
            die("Cannot connect to Database");
        }
    }

    /**
     * Exec the proceures
     * @param String $strSql  the parameters should be use (?,?,?...?)
     * @param Array $Parameters the values in the array
     * @return type
     */
    public function execProcedures($strSql, $Parameters) {
        $pdoStatement = $this->PDO->prepare($strSql);
        $pdoStatement->setFetchMode(PDO::FETCH_ASSOC);
        // bind the parameter
        $i = 1;
        foreach ($Parameters as $value) {
            $pdoStatement->bindValue($i++, $value);
        }

        $pdoStatement->execute();
        $res = $pdoStatement->fetchAll();
        if ($pdoStatement->errorCode() == "00000") {
            return $res;
        } else {
            print_r($pdoStatement->errorInfo());
            die("query in Database is error ");
        }
    }

    /**
     * 
     * @param type $strSql
     */
    public function execSqlStatement($strSql) {
        $pdoStatement = $this->PDO->query($strSql);
        $pdoStatement->setFetchMode(PDO::FETCH_ASSOC);
        $res = $pdoStatement->fetchAll();
        if ($pdoStatement->errorCode() == "00000") {
            return $res;
        } else {
            print_r($pdoStatement->errorInfo());
            die("query in Database is error ");
        }
    }

    /**
     * return the PDO DbHelperObject
     * @return type
     */
    public function getDbh() {
        return $this->PDO;
    }

}

?>
